package com.brook.app.android.filepicker;

import android.content.Context;
import androidx.annotation.NonNull;
import android.util.Log;

import com.brook.app.android.filepicker.core.ImageFileProvider;
import com.brook.app.android.filepicker.core.FilePickCallback;
import com.brook.app.android.filepicker.core.FilePickerConfig;
import com.brook.app.android.filepicker.core.FilePickerConfigRegistry;
import com.brook.app.android.filepicker.core.MimeType;
import com.brook.app.android.filepicker.core.VideoPickerConfig;

/**
 * @author Brook
 * @time 2020-03-14 10:29
 */
public class FilePickerUtils {

    public static final String TAG = "FilePicker";


    private FilePickerConfig mConfig;

    public FilePickerUtils(FilePickerConfig config) {
        mConfig = config;
    }

    public static FilePickerConfig createImageConfig() {
        FilePickerConfig config = createByConfig(FilePickerConfig.class);
        config.addFileProvider(new ImageFileProvider());
        config.setPickerMimeType(MimeType.IMAGE.toString());
        return config;
    }

    public static VideoPickerConfig createVideoConfig() {
        return createByConfig(VideoPickerConfig.class);
    }

    @NonNull
    public static <T extends FilePickerConfig> T createByConfig(Class<T> filePickerConfig) {
        try {
            return filePickerConfig.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 合并默认的配置
     *
     * @return
     */
    public FilePickerUtils mergeDefaultConfig() {
        mConfig.resetBy(FilePickerConfigRegistry.getDefaultConfig());
        return this;
    }

    /**
     * 启动UI选择
     * @param context
     * @param callback
     */
    public void launchPicker(@NonNull Context context, FilePickCallback callback) {
        if (mConfig == null) {
            mConfig = FilePickerConfigRegistry.getDefaultConfig();
        }

        if (mConfig.getProvider(mConfig.getPickerMimeType()) == null) {
            Log.e(TAG, "file provider not found");
            return;
        }
        mConfig.setApplicationContext(context.getApplicationContext());
        mConfig.setCallback(callback);
        mConfig.startLaunchPickerUI(context);
    }
}
